/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Modele;

import java.util.Stack;
import java.util.TreeSet;

/**
 *
 * @author Gloire
 */
public class SolverV2 {
    
    private TreeSet<String> result;
    private Dictionnaire dico;
    
    private Case[][] grille;
    
    public SolverV2(Case[][] c,Dictionnaire d){
        dico = d;
        result = RuzzleSolver(c);
    }
    
    public TreeSet<String> getResult(){
        return this.result;
    }
    
    public Dictionnaire getDico(){
        return this.dico;
    }
    
    @Override
    public String toString(){
        String retour = "";
        for(String mot : this.result)
            retour += mot+"\n";
        retour += "il y avait "+this.result.size()+" solutions";
        return retour;
    }
    
    public TreeSet<String> RuzzleSolver(Case[][] grille) {
        if (grille == null) {
            throw new NullPointerException("la grille est null");
        }
        result = new TreeSet();
        Stack<Case> pile = new Stack();
        for(int i = 0; i < grille.length; i++)
            for(Case c : grille[i])
                solve(c,c.toString(), pile);
        return result;
    }

    private void solve(Case c, String prefix, Stack<Case> visitees) {
        if(dico.existe(prefix)){
            result.add(prefix);
        }
        if(!dico.commence(prefix)){
            return;
        }
        Stack<Case> parcours = new Stack();
        parcours.addAll(visitees);
        parcours.add(c);
        for(Case d : c.getVoisins()){
            if(!parcours.contains(d))
                solve(d,prefix+d.toString(),parcours);
        }

    }
    
}
